package response

import (
	"day12_11_homework/config"
	"day12_11_homework/internal/models/dao"
	"day12_11_homework/internal/models/service"
	"day12_11_homework/pkg"
	"strconv"
	"time"
)

func UserLoginResponse(tel string, password string) (int, string) {
	user, err := service.Login(tel)
	if err != nil {
		redis := UserLoginResponseRedis(tel)
		if redis != "" {
			return 0, redis
		}
		return 0, "登录失败"
	}
	if user.ID == 0 {
		redis := UserLoginResponseRedis(tel)
		if redis != "" {
			return 0, redis
		}
		return 0, "登录失败"
	}
	password = password + "1234"
	if pkg.Md5(password) != user.Password {
		redis := UserLoginResponseRedis(tel)
		if redis != "" {
			return 0, redis
		}
		return 0, "登录失败"
	}

	return int(user.ID), ""
}

func UserRegisterResponse(user *dao.User, tel string, code string) string {
	sms := GetSendSms(tel, code)
	if sms != "" {
		return sms
	}
	err := service.Register(user)
	if err != nil {
		return "注册失败"
	}
	return ""
}

func UserLoginResponseRedis(tel string) string {
	Num := "login_num_" + tel
	config.Rdb.Incr(config.Ctx, Num)
	config.Rdb.Expire(config.Ctx, Num, time.Hour*1)
	get := config.Rdb.Get(config.Ctx, Num)
	if get.Val() > "3" {
		return "登录失败太多次，请稍后再试"
	}
	return ""
}

func UpdateStatusResponse(id int) string {
	err := service.UpdateStatus(id)
	if err != nil {
		return "修改失败"
	}
	return ""
}

func DelUser(id any) (int, string) {
	s := id.(string)
	ids, _ := strconv.Atoi(s)
	if ids == 0 {
		return 0, "登录状态异常"
	}
	return ids, ""
}
